package dao

import (
	"cms/model"
	"cms/store"
	"cms/utils/convert"
	"fmt"
	uuid "github.com/satori/go.uuid"
	"github.com/wdaglb/korm"
)

// AdminLogin 后台用户登陆
func AdminLogin(user string, pass string) (string, int, error) {
	db := korm.NewContext()
	row := &model.Admin{}
	coll := db.Model(&row).Where("Username", user).Find()
	if !coll.Exist {
		return "", 0, fmt.Errorf("账号不存在")
	}
	if coll.Error != nil {
		return "", 0, coll.Error
	}
	if !convert.PasswordVerify(pass, row.Password) {
		return "", 0, fmt.Errorf("密码错误")
	}

	// 生成权限令牌
	tok := convert.Md5(uuid.NewV4().String() + row.Username)
	expire := 7200
	if err := store.SetAdminToken(row.Username, tok, expire); err != nil {
		return "", 0, err
	}
	return tok, expire, nil
}

// AdminLogout 注销登陆
func AdminLogout(token string) error {
	if err := store.RemoveAdminToken(token); err != nil {
		return err
	}

	return nil
}
